package model;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class LectorTS {
	static private int comp = 0x47;
	static private int length_ts = 188;
	private FileOutputStream file;
	private int cant = 0;

	public LectorTS(String path) throws FileNotFoundException{
		this.file = new FileOutputStream(path);
	}
	
	public boolean sync(String path) throws IOException {
		FileInputStream file = new FileInputStream(path);
		boolean ret = true;
		int contador = 0;
		boolean tieneInicio = false;
		while (file.available() > 0) {
			if ((byte) file.read() == comp) {
				tieneInicio = true;
				break;
			}
			contador++;
			System.out.println("no entro mas");
		}
		if (tieneInicio) {
			boolean estaSync = true;
			byte value = 0;
			while (estaSync && file.available() > 0) {
				file.skip(187);
				if (file.available() > 0) {
					estaSync &= (value = (byte) file.read()) == 71;
				}
				contador += length_ts;
			}
			ret = estaSync;
		}
		return ret;
	}

	// public void pid(String path) throws IOException{
	// FileInputStream file = new FileInputStream(path);
	// byte value;
	// byte value2;
	//
	// file.skip(1);
	// value = (byte) file.read();
	// file.skip(1);
	// value2 = (byte) file.read();
	//
	//
	//
	// }

	public int pid(byte b1, byte b2) {
		int ret;
		int a = (b1 & 0x001F) << 8;
		int b = b2 & 0x00FF;

		ret = a | b;

		return ret;
	}

	public void imprimirPids(String path) throws IOException {

		if (this.sync(path)) {
			FileInputStream file = new FileInputStream(path);
			while (file.available() > 0) {
				file.skip(1);
				byte b = (byte)file.read();
				byte b1 = (byte)file.read();
				file.skip(185);
				int pid = this.pid(b, b1);

				String s = String.format("%02x", pid);
				System.out.println(s);
			}

		} else {
			System.out.println("el archivo ts no esta sincronizado");
		}
	}
	public void recopilar(String path, int c) throws IOException{
		FileInputStream fileI = new FileInputStream(path);
		for(int i = 0; i < c ; i++){
			for(int r = 0; r < 188; r++){
			this.file.write(fileI.read());
			};
		}
	}

	public static void main(String args[]) throws IOException {

		LectorTS p = (new LectorTS("/home/mauro/Escritorio/prueba.ts"));
		p.recopilar("/home/mauro/Escritorio/sample521.ts", 5);
	}

	/**
	 * @return the cant
	 */
	public int getCant() {
		return cant;
	}

	/**
	 * @param cant the cant to set
	 */
	public void setCant(int cant) {
		this.cant = cant;
	}
}